import { ref, toRefs, reactive, nextTick, getCurrentInstance } from "vue"
import { ElMessage } from "element-plus"
import Query from "../../../zondy/lib/Query.js"
import { useMapStore } from "../../store/useMap.js"
const { mapState } = toRefs(useMapStore())
export const useManagerEvent = () => {
  const { $echarts } = getCurrentInstance().appContext.config.globalProperties
  const eventData = ref([])
  const eventFID = []
  const dialogEventDetails = ref(false)
  const echartsDialog = ref(false)
  const updataEventResult = ref(null)
  const updataID = ref(0)
  const eventManagerService = { name: "traffic", layerId: 2 }
  const eventForm = reactive({
    eventNumber: "",
    dirverName: "",
    carNumber: "",
    eventPlace: "",
    eventDate: "",
    eventGrade: "",
    eventType: "",
  })
  const myechats = ref(null)
  function queryManager() {
    mapState.value.dialogTableVisible = true
    Query.queryByLayer({ service: eventManagerService, success: queryManagerEventSuccess })
  }
  function queryManagerEventSuccess(e) {
    eventData.value = []
    e.SFEleArray.forEach(item => {
      eventFID.push(item.FID)
    })
    var format = new Zondy.Format.PolygonJSON()
    /* 将mapgis要素json反序列化为ol.feature类型数组 */
    var features = format.read(e)
    /* 将查询到的要素添加到高亮图层中 */
    features.forEach(item => {
      eventData.value.push(item.values_.values_)
    })
    for (let i = 0; i < eventData.value.length; i++) {
      eventData.value[i].FID = eventFID[i]
    }
    mapState.value.eventData = eventData.value
  }
  function handleDelete(scope) {
    var deleteService = new Zondy.Service.EditDocFeature(eventManagerService.name, eventManagerService.layerId, {})
    deleteService.deletes(scope.row.FID, onPntSuccess(mapState.value.docLayer))
    eventData.value.forEach((item, index) => {
      if (item.FID == scope.row.FID) {
        mapState.value.eventData.splice(index, 1)
      }
    })
  }
  function handleEdit(scope) {
    updataID.value = scope.row.FID
    dialogEventDetails.value = true
    eventForm.eventNumber = scope.row.事件编号
    eventForm.carNumber = scope.row.车牌号
    eventForm.dirverName = scope.row.驾驶员
    eventForm.eventPlace = scope.row.发生地点
    eventForm.eventDate = scope.row.发生时间
    eventForm.eventGrade = scope.row.事件等级
    eventForm.eventType = scope.row.事件类型
    Query.queryByFid({ service: eventManagerService, fid: scope.row.FID, success: handleEditSuccess })
  }
  function handleEditSuccess(result) {
    updataEventResult.value = result
  }
  function onSubmitUpdate() {
    var editService = new Zondy.Service.EditDocFeature(eventManagerService.name, eventManagerService.layerId, {})
    updataEventResult.value.SFEleArray[0].AttValue[0] = eventForm.eventNumber
    updataEventResult.value.SFEleArray[0].AttValue[1] = eventForm.eventType
    updataEventResult.value.SFEleArray[0].AttValue[2] = eventForm.eventGrade
    updataEventResult.value.SFEleArray[0].AttValue[3] = eventForm.eventDate
    updataEventResult.value.SFEleArray[0].AttValue[4] = eventForm.eventPlace
    updataEventResult.value.SFEleArray[0].AttValue[5] = eventForm.carNumber
    updataEventResult.value.SFEleArray[0].AttValue[6] = eventForm.dirverName
    editService.update(updataEventResult.value, updateEventSuccess(mapState.value.docLayer))
  }
  function updateEventSuccess(docLayer) {
    return function (result) {
      if (result) {
        // eventData.value.forEach(item => {
        //   if (item.FID == updataID.value) {
        //     item.事件等级 = eventForm.eventGrade
        //     item.事件类型 = eventForm.eventType
        //     item.事件编号 = eventForm.eventNumber
        //     item.发生地点 = eventForm.eventPlace
        //     item.发生时间 = eventForm.eventDate
        //     item.车牌号 = eventForm.carNumber
        //     item.驾驶员 = eventForm.dirverName
        //   }
        // })
        dialogEventDetails.value = false
        ElMessage({
          message: "修改事件成功",
          type: "success",
          duration: 2000,
        })
        queryManager()
        docLayer.refresh()
        mapState.value.map.renderSync()
      } else {
        ElMessage({
          message: "修改事件失败",
          type: "error",
          duration: 2000,
        })
      }
    }
  }
  function onPntSuccess(docLayer) {
    return function (result) {
      if (result) {
        ElMessage({
          message: "删除事件成功",
          type: "success",
          duration: 2000,
        })
        docLayer.refresh()
        mapState.value.map.renderSync()
      } else {
        ElMessage({
          message: "删除事件失败",
          type: "error",
          duration: 2000,
        })
      }
    }
  }
  function cancelUpdate() {
    dialogEventDetails.value = false
  }

  function getEcharts() {
    echartsDialog.value = true
    const typeNum = [0, 0, 0, 0, 0, 0]
    mapState.value.eventData.forEach(item => {
      if (item.事件类型 == "其他") {
        typeNum[0] += 1
      } else if (item.事件类型 == "失火") {
        typeNum[1] += 1
      } else if (item.事件类型 == "碾压") {
        typeNum[2] += 1
      } else if (item.事件类型 == "翻车") {
        typeNum[3] += 1
      } else if (item.事件类型 == "刮擦") {
        typeNum[4] += 1
      } else if (item.事件类型 == "碰撞") {
        typeNum[5] += 1
      }
    })

    nextTick(() => {
      $echarts.init(myechats.value).dispose()
      const eventChart = $echarts.init(myechats.value)
      eventChart.setOption({
        bottom: "50%",
        title: {
          text: "事件类型统计",
          textStyle: {
            color: "rgba(64,158,255,1)", // 标题颜色
            fontSize: 18,
            lineHeight: 20,
          },
        },
        grid: {
          left: "4%",
          right: "4%",
          bottom: "5%",
          containLabel: true,
        },
        tooltip: {},
        xAxis: {
          data: ["其他", "失火", "碾压", "翻车", "刮擦", "碰撞"],
        },
        yAxis: {},
        series: [
          {
            name: "数量",
            type: "bar",
            data: typeNum,
          },
        ],
      })
    })
  }
  function getPieEcharts() {
    echartsDialog.value = true
    const levelNum = [
      { value: 0, name: "等级1" },
      { value: 0, name: "等级2" },
      { value: 0, name: "等级3" },
      { value: 0, name: "等级4" },
    ]
    mapState.value.eventData.forEach(item => {
      if (item.事件等级 == "1") {
        levelNum[0].value += 1
      } else if (item.事件等级 == "2") {
        levelNum[1].value += 1
      } else if (item.事件等级 == "3") {
        levelNum[2].value += 1
      } else if (item.事件等级 == "4") {
        levelNum[3].value += 1
      }
    })
    nextTick(() => {
      $echarts.init(myechats.value).dispose()
      const lavelChart = $echarts.init(myechats.value)
      lavelChart.setOption({
        tooltip: {},
        bottom: "50%",
        title: {
          text: "事件等级统计",
          textStyle: {
            color: "rgba(64,158,255,1)", // 标题颜色
            fontSize: 18,
            lineHeight: 20,
          },
        },
        grid: {
          left: "4%",
          right: "4%",
          bottom: "5%",
          containLabel: true,
        },
        series: [
          {
            name: "数量",
            type: "pie",
            radius: "55%",
            data: levelNum,
          },
        ],
      })
    })
  }
  return { queryManager, handleDelete, handleEdit, eventForm, dialogEventDetails, onSubmitUpdate, cancelUpdate, getEcharts, myechats, echartsDialog, getPieEcharts }
}
